/*
 * Copyright (C) 2006 Johan Maasing johan at zoom.nu Licensed under the Apache
 * License, Version 2.0 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
 * or agreed to in writing, software distributed under the License is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */
package nu.zoom.catonine.swing.rule;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.SortedMap;

import javax.swing.DefaultComboBoxModel;

import nu.zoom.catonine.stylerule.StyleRules;

/**
 * A list model to display the available character sets.
 * 
 * @author "Johan Maasing" &lt;johan@zoom.nu&gt;
 * 
 */
public class CharsetListModel extends DefaultComboBoxModel {

	private static final long serialVersionUID = 1L;
	private static List<Charset> charsets = new ArrayList<Charset>();
	private StyleRules list;

	public CharsetListModel(StyleRules tailer) {
		super();
		this.list = tailer;
		synchronized (charsets) {
			if (charsets.size() < 1) {
				SortedMap<String, Charset> map = Charset.availableCharsets();
				ArrayList<Charset> list = new ArrayList<Charset>();
				for (Charset charset : map.values()) {
					list.add(charset);
				}
				charsets = Collections.unmodifiableList(list);
			}
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.swing.DefaultComboBoxModel#getElementAt(int)
	 */
	@Override
	public Object getElementAt(int index) {
		return CharsetListModel.charsets.get(index);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.swing.DefaultComboBoxModel#getSize()
	 */
	@Override
	public int getSize() {
		return CharsetListModel.charsets.size();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.swing.DefaultComboBoxModel#setSelectedItem(java.lang.Object)
	 */
	@Override
	public void setSelectedItem(Object anObject) {
		if ((anObject != null) && (anObject instanceof Charset)) {
			list.setFileEncoding(((Charset) anObject).name());
			super.setSelectedItem(anObject);
		}
	}
}
